package org.sbbs.base.jpa.manager.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.sbbs.base.jpa.dao.BaseTreeRepo;
import org.sbbs.base.jpa.entity.BaseTreeEntity;
import org.sbbs.base.jpa.manager.BaseTreeCacheManager;
import org.springframework.data.domain.Example;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author jenkins Manager体系原则上是负责实体数据管理功能
 * @param <T>
 * @param <ID>
 */
@Transactional(readOnly = false, rollbackFor = Throwable.class)
public class BaseTreeCacheManagerImpl<T extends BaseTreeEntity, ID extends Serializable, R extends BaseTreeRepo<T, ID>> extends BaseManagerCacheImpl<T, ID, R> implements BaseTreeCacheManager<T, ID, R> {

    private BaseTreeRepo<T, ID> repo;

    @Override
    public List<T> findChildren(T pid) {
//        List<T> sa = this.repo.findByPidOrderBySort(pid.getId());
        List<Long> ids = this.repo.findIdByPidOrderBySort(pid.getId());
        List<T> sa = new ArrayList<>();
        for (Long id : ids) {
            T t = this.findById((ID) id);
            t.setParent(pid);
            this.getCache().put(id, t);
            sa.add(t);
        }
        return sa;
    }

    @Override
    public Boolean hasChildren(T p) {
        try {
            T e = (T) p.getClass().newInstance();
            e.setPid(p.getId());
            Example<T> em = Example.of(e);
            return repo.exists(em);
        } catch (InstantiationException | IllegalAccessException | SecurityException ex) {
            Logger.getLogger(BaseTreeCacheManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
//        return repo.exists(em);
    }

    @Override
    public void updateChildrenSort(List<T> children) {
        for (int i = 0; i < children.size(); i++) {
            T get = children.get(i);
            get.setSort(i);
        }
        this.saveAll(children);
//        this.repo.saveAllAndFlush(children);
    }
//        @Override
//    public BaseTreeRepo<T, ID> getRepo() {
//        return this.repo;
//    }

    public void setRepo(BaseTreeRepo<T, ID> rep) {
        this.repo = rep;
        super.setRepo(rep);
    }

    @Override
    public List<Long> findIdByPidOrderBySort(Long pid) {
        return this.repo.findIdByPidOrderBySort(pid);
    }
}
